﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WqLunTan.Filters;
using WqLunTan.Models.DataBase;
using Microsoft.Extensions.DependencyInjection;
using System.IO;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using WqLunTan.Areas.Manage.Models;

namespace WqLunTan.Areas.Manage.Controllers
{
    /// <summary>
    /// 后台文章管理控制器
    /// </summary>
    [Auth(AuthType = WqUserAuth.Manage)]
    public class CategoryController : BaseManageController
    {
        /// <summary>
        /// 显示所有的文章分类
        /// </summary>
        /// <returns></returns>
        public IActionResult List()
        {
            var list = DbContext.art_category.OrderByDescending(x => x.is_show).ThenBy(x => x.sort).ThenBy(x => x.create_time).ToList();
            return View(list);
        }

        /// <summary>
        /// 可查看的分类文章
        /// </summary>
        /// <returns></returns>
        public IActionResult ArticleList(Guid id, string search, int pageIndex = 1, int pageSize = 20)
        {
            List<article> list;

            var query = DbContext.article.Where(x => x.is_show && x.cateid == id);
            var page = new PageModel() { CurrentPageIndex = pageIndex };
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(x => x.title.Contains(search) || x.keywords.Contains(search));
                page.TotalCount = query.Count();
                list = query.OrderByDescending(x => x.top).ThenBy(x => x.sort_num).ThenByDescending(x => x.create_time).Skip(pageSize * pageIndex - pageSize).Take(pageSize).ToList();
            }
            else
            {
                page.TotalCount = query.Count();
                list = query.OrderByDescending(x => x.top).ThenBy(x => x.sort_num).ThenByDescending(x => x.create_time).Skip(pageSize * pageIndex - pageSize).Take(pageSize).ToList();
            }

            var uidlist = list.Select(x => x.uid).ToList();
            if (uidlist.Count > 0)
            {
                var ulist = DbContext.Users.Where(x => uidlist.Contains(x.Id)).ToList();
                ViewData["ulist"] = ulist;
            }
            else
            {
                ViewData["ulist"] = new List<WqUser>();
            }

            var cate = DbContext.art_category.OrderByDescending(x => x.is_show).ThenBy(x => x.sort).ThenBy(x => x.create_time).ToList();

            ViewData["cateid"] = id;
            ViewData["page"] = page;
            ViewData["list"] = list;
            ViewData["cate"] = cate;
            ViewData["is_show"] = true;
            ViewData["show-count"] = DbContext.article.Where(x => x.is_show && x.cateid == id).Count();
            ViewData["hide-count"] = DbContext.article.Where(x => x.is_show == false && x.cateid == id).Count();
            return View();
        }

        public IActionResult HideArticleList(Guid id, string search, int pageIndex = 1, int pageSize = 20)
        {
            List<article> list;

            var query = DbContext.article.Where(x => x.is_show == false && x.cateid == id);
            var page = new PageModel() { CurrentPageIndex = pageIndex };
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(x => x.title.Contains(search) || x.keywords.Contains(search));
                page.TotalCount = query.Count();
                list = query.OrderByDescending(x => x.top).ThenBy(x => x.sort_num).ThenByDescending(x => x.create_time).Skip(pageSize * pageIndex - pageSize).Take(pageSize).ToList();
            }
            else
            {
                page.TotalCount = query.Count();
                list = query.OrderByDescending(x => x.top).ThenBy(x => x.sort_num).ThenByDescending(x => x.create_time).Skip(pageSize * pageIndex - pageSize).Take(pageSize).ToList();
            }

            var uidlist = list.Select(x => x.uid).ToList();
            if (uidlist.Count > 0)
            {
                var ulist = DbContext.Users.Where(x => uidlist.Contains(x.Id)).ToList();
                ViewData["ulist"] = ulist;
            }
            else
            {
                ViewData["ulist"] = new List<WqUser>();
            }

            var cate = DbContext.art_category.OrderByDescending(x => x.is_show).ThenBy(x => x.sort).ThenBy(x => x.create_time).ToList();

            ViewData["cateid"] = id;
            ViewData["page"] = page;
            ViewData["list"] = list;
            ViewData["cate"] = cate;
            ViewData["is_show"] = false;
            ViewData["show-count"] = DbContext.article.Where(x => x.is_show && x.cateid == id).Count();
            ViewData["hide-count"] = DbContext.article.Where(x => x.is_show == false && x.cateid == id).Count();
            return View("ArticleList");
        }

        public IActionResult Add()
        {
            return View();
        }

        public IActionResult Save(article_category category, IFormFile img)
        {
            if (img == null)
            {
                return JsonParamError("图标不能为空");
            }

            if (string.IsNullOrWhiteSpace(category.category_name))
            {
                return JsonParamError("分类名称不能为空");
            }

            if (img != null)
            {
                var env = HttpContext.RequestServices.GetService<IHostingEnvironment>();
                var root = env.WebRootPath;

                var day = DateTimeOffset.UtcNow.ToString("yyyy-MM-dd");

                var ext = img.FileName.Substring(img.FileName.LastIndexOf('.'));
                var name = $"{Guid.NewGuid().ToString("N")}{ext}";
                var filename = Path.Combine(root, "upload", "image", day, name);
                var fi = new FileInfo(filename);
                if (!Directory.Exists(fi.DirectoryName))
                {
                    Directory.CreateDirectory(fi.DirectoryName);
                }

                using (var ms = new MemoryStream())
                {
                    // 读取图片
                    img.CopyTo(ms);
                    var bytes = ms.ToArray();

                    // 图片缩放
                    using (Image<Rgba32> imageSharp = Image.Load(bytes))
                    {
                        if (imageSharp.Width >= imageSharp.Height)
                        {
                            imageSharp.Mutate(x => x.Resize(400, imageSharp.Height * 400 / imageSharp.Width));
                        }
                        else
                        {
                            imageSharp.Mutate(x => x.Resize(imageSharp.Width * 400 / imageSharp.Height, 400));
                        }

                        // 保存图片为磁盘文件
                        imageSharp.Save(filename);

                        var fileUrl = $"/upload/image/{day}/{name}";
                        category.img = fileUrl;
                    }
                }
            }

            category.create_time = DateTimeOffset.UtcNow;
            category.last_update = DateTimeOffset.UtcNow;
            DbContext.art_category.Add(category);
            DbContext.SaveChanges();

            return JsonOkResult("保存成功");
        }

        /// <summary>
        /// 详情页
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult Detail(Guid id)
        {
            var model = DbContext.art_category.Where(x => x.id == id).SingleOrDefault() ?? new article_category();

            return View(model);
        }

        public IActionResult Update(article_category category, IFormFile img)
        {
            var model = DbContext.art_category.Where(x => x.id == category.id).SingleOrDefault();
            if (model != null)
            {
                model.last_update = DateTimeOffset.UtcNow;
                model.category_name = category.category_name;
                model.sort = category.sort;
                model.is_show = category.is_show;

                if (img != null)
                {
                    var env = HttpContext.RequestServices.GetService<IHostingEnvironment>();
                    var root = env.WebRootPath;

                    var day = DateTimeOffset.UtcNow.ToString("yyyy-MM-dd");

                    var ext = img.FileName.Substring(img.FileName.LastIndexOf('.'));
                    var name = $"{Guid.NewGuid().ToString("N")}{ext}";
                    var filename = Path.Combine(root, "upload", "image", day, name);
                    var fi = new FileInfo(filename);
                    if (!Directory.Exists(fi.DirectoryName))
                    {
                        Directory.CreateDirectory(fi.DirectoryName);
                    }

                    using (var ms = new MemoryStream())
                    {
                        // 读取图片
                        img.CopyTo(ms);
                        var bytes = ms.ToArray();

                        // 图片缩放
                        using (Image<Rgba32> imageSharp = Image.Load(bytes))
                        {
                            if (imageSharp.Width >= imageSharp.Height)
                            {
                                imageSharp.Mutate(x => x.Resize(400, imageSharp.Height * 400 / imageSharp.Width));
                            }
                            else
                            {
                                imageSharp.Mutate(x => x.Resize(imageSharp.Width * 400 / imageSharp.Height, 400));
                            }

                            // 保存图片为磁盘文件
                            imageSharp.Save(filename);

                            // 删除旧图片
                            if (!string.IsNullOrWhiteSpace(model.img))
                            {
                                var oldImage = $"{root.Replace('\\', '/').TrimEnd('/')}{model.img}";
                                if (System.IO.File.Exists(oldImage))
                                {
                                    System.IO.File.Delete(oldImage);
                                }
                            }

                            var fileUrl = $"/upload/image/{day}/{name}";
                            model.img = fileUrl;
                        }
                    }
                }

                DbContext.SaveChanges();
            }

            return JsonOkResult("保存成功");
        }
    }
}